import { defineStore } from 'pinia';

import { apiGetListGroup } from '@/api/ice/client';
import { utListToTree } from '@/utils/ice';
import { getAuthCache, setAuthCache } from '@/utils/auth';
import { COMMON_STRATEGY } from '@/enums/cacheEnum';

interface ClientIce {
  groupList: [];
  groupTree: []; // 终端分组树列表
  groupSource: {}; // 终端分组源文件
  aCommonStrategy: []; // 常用策略
  clientTotal: Number; // 客户端总数
}

export const useIceStore = defineStore({
  id: 'table-ice',
  state: (): ClientIce => ({
    groupSource: {},
    groupList: [],
    groupTree: [],
    clientTotal: 0,
    aCommonStrategy: [],
  }),
  getters: {
    getGroupList(state): [] {
      return state.groupList;
    },
    getClientTotal(state): Number {
      return state.clientTotal;
    },
    getGroupSource(state): {} {
      return state.groupSource;
    },
    getGroupTree(state): [] {
      return state.groupTree;
    },
    getCommonStrategy(state): [] {
      //@ts-ignore
      return state.aCommonStrategy.length
        ? (state.aCommonStrategy as [])
        : getAuthCache<string>(COMMON_STRATEGY);
    },
  },
  actions: {
    async setGroupList() {
      const { list, total } = await apiGetListGroup({ name: '' });
      const tempList = updateClientCount(list || []);
      this.clientTotal = total as number;
      this.groupTree = utListToTree(tempList as []) as [];
      this.groupList = tempList as [];
      this.groupSource = tempList.reduce((obj, item) => {
        obj[item.id] = item;
        return obj;
      }, {});
    },
    setCommonStrategy(data: []) {
      const tempList = (this.getCommonStrategy || []).map((res) => res);
      const tempListB = (data || []).map((res) => res);
      const mergedArray = tempList.concat(tempListB);
      //@ts-ignore
      this.aCommonStrategy = mergedArray.filter(
        //@ts-ignore
        (item, index, self) => self.findIndex((t) => t.id === item.id) === index,
      );
      setAuthCache(COMMON_STRATEGY, this.aCommonStrategy);
    },
  },
});
function updateClientCount(data) {
  // 创建一个对象来存储每个 id 的子节点总数
  const childCounts = Object.fromEntries(data.map((item) => [item.id, 0]));

  // 从底层开始向上更新
  for (let i = data.length - 1; i >= 0; i--) {
    const item = data[i];

    // 更新当前项的 client_count
    item.client_count += childCounts[item.id] || 0;

    // 如果有父节点，更新父节点的 childCounts
    if (item.pid !== 0) {
      childCounts[item.pid] = (childCounts[item.pid] || 0) + item.client_count;
    }
  }

  return data;
}
